Skip to content

Fix closure with block body followed by method call (issue #4050)#6900

Closed
tao501 wants to merge 1 commit into
rust-lang:mainfrom
tao501:fix-issue-4050
Closed

Fix closure with block body followed by method call (issue #4050)#6900
tao501 wants to merge 1 commit into
rust-lang:mainfrom
tao501:fix-issue-4050

Conversation

@tao501
Copy link
Copy Markdown

@tao501 tao501 commented May 17, 2026

Description

Fix for rustfmt issue #4050: "Rustfmt changes meaning of closure, also not idempotent"

Problem

When a closure with a block body is followed by a method call (e.g., || { ... }().to_string()), rustfmt incorrectly formats it as:

|| { { println!(); || 0 }().to_string(); }

This changes the program's semantics from ((|| {...}())..to_string()) to || {({...}()..to_string());}.

Root Cause

In src/chains.rs, the should_add_parens() function returns false for closures with block bodies, so the chain formatter doesn't add the necessary parentheses around the closure call before the method call.

Fix

Added ast::ExprKind::Block(..) => true to the closure match in should_add_parens(), ensuring that closures with block bodies get parenthesized when followed by method calls.

This produces the correct output:

(|| { println!(); || 0 }()).to_string()

Closes #4050

@rustbot rustbot added the S-waiting-on-review Status: awaiting review from the assignee but also interested parties. label May 17, 2026
@tao501 tao501 force-pushed the fix-issue-4050 branch 4 times, most recently from f8d7e01 to ae40c17 Compare May 17, 2026 14:32
@ytmimi
Copy link
Copy Markdown
Contributor

ytmimi commented May 22, 2026

Because of suspected low effort AI PR in #6901 I'm going to close this PR too.

@ytmimi ytmimi closed this May 22, 2026
@rustbot rustbot removed the S-waiting-on-review Status: awaiting review from the assignee but also interested parties. label May 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Rustfmt changes meaning of closure, also not idempotent

3 participants